package com.tkjt.pms.modules.performances.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tkjt.pms.common.entity.TkIndexReport;
import com.tkjt.pms.common.entity.TkIndexValue;
import com.tkjt.pms.common.utils.DepartCode;
import com.tkjt.pms.common.utils.EsDateUtils;
import com.tkjt.pms.common.utils.EsJsonUtils;
import com.tkjt.pms.common.utils.TkIndexUtils;
import com.tkjt.pms.common.vos.TkIndexValueMirrorVo;
import com.tkjt.pms.modules.common.mapper.PMSCommonMapper;
import com.tkjt.pms.modules.common.service.TkDataConfigService;
import com.tkjt.pms.modules.kpiAudit.model.kpiAuditrowList.YearModel;
import com.tkjt.pms.modules.performances.constant.CalcuConsts;
import com.tkjt.pms.modules.performances.constant.IndexCommonRepositories;
import com.tkjt.pms.modules.performances.constant.IndexValueCodesRepositories;
import com.tkjt.pms.modules.performances.mapper.PerformancesMapper;
import com.tkjt.pms.modules.performances.model.reportrowList.IndexReportVO;
import com.tkjt.pms.modules.performances.model.reportrowList.ReportrowListModel;
import com.tkjt.pms.modules.performances.model.vos.IndexValueVo;
import com.tkjt.pms.modules.performances.service.PerformancesService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Transactional
@Service
public class PerformancesServiceImpl extends ServiceImpl<PerformancesMapper, TkIndexValue> implements PerformancesService {

    @Autowired
    ISysDictItemService sysDictItemService;
    @Autowired
    PMSCommonMapper commonMapper;
    @Autowired
    private TkDataConfigService tkDataConfigService;

    @Override
    public ReportrowListModel getMyReportrowList(LoginUser loginUser, HttpServletRequest request) {
        String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
        ReportrowListModel model=new ReportrowListModel();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        if (month == 0) {
            year = year - 1;
        }
        model.setDefaulYear(year+"");
        model.setYearList(getYearList());
        model.setIndexReportVOList(getIndexReportVOList(request,dataType));
        return model;
    }

    @Override
    public List<IndexValueVo> getDetailDatagrid(LoginUser loginUser,HttpServletRequest request) {
        String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
        TkIndexValue tkIndexValueEntity = new TkIndexValue();
        String indexDepart = request.getParameter("indexDepart");//A01A01A01A01
        List<String> indexValueCodes = new ArrayList<>();
        if (null != indexDepart && !"".equals(indexDepart)) {
            if ("A01A01A01".equals(indexDepart.substring(0, 9))) {
                // 一线 --- 得分指标编码
                List<String> tmpList = IndexValueCodesRepositories.getScoreIndexValueCodes(CalcuConsts.INDEX_UNIT);
                if(null != tmpList) {
                    indexValueCodes = new ArrayList<>(tmpList);
                }

            } else {
                // 本部 --- 得分指标编码
                List<String> tmpList = IndexValueCodesRepositories.getScoreIndexValueCodes(CalcuConsts.INDEX_GROUP);
                if(null != tmpList) {
                    indexValueCodes = new ArrayList<>(tmpList);
                }

            }
            tkIndexValueEntity.setIndexDepart(indexDepart);
            String indexYear = EsDateUtils.getIndexYear(EsDateUtils.getIndexYearMonth(new Date()));
            return loadMirrorMTotalIndexValues(indexYear, indexDepart, indexValueCodes,dataType);
        }


        return null;
    }

    public List<IndexValueVo> loadMirrorMTotalIndexValues(String indexYear, String indexDepartCode, List<String> indexValueCodes,String dataType) {

        List<IndexValueVo> voResults = new ArrayList<>();
        // mirrorCodes必有有序，月份从小到大
        List<String> mirrorCodes = IndexCommonRepositories.getMirrorCodes(indexYear);
        log.info("load mirror values, start...");
        log.info(mirrorCodes.toString());
        Map<String, Map<String, Object>> icMap = new HashMap<>();
        for (String mirrorCode : mirrorCodes) {
            List<TkIndexValueMirrorVo> entities = getMirrorIndexValueEntities(indexDepartCode, mirrorCode, indexValueCodes,dataType);
            for (TkIndexValueMirrorVo entity : entities) {
                String tempIndexValueCode = entity.getIndexValueCode();
                Map<String, Object> tmpVo = icMap.get(tempIndexValueCode);
                if (tmpVo == null) {
                    tmpVo = new HashMap<>();
                    icMap.put(tempIndexValueCode, tmpVo);
                    tmpVo.put("year", indexYear);
                    tmpVo.put("indexDepart", entity.getIndexDepart());
                    tmpVo.put("indexGroup", TkIndexUtils.getIndexGroupNumber(tempIndexValueCode));
//                    tmpVo.put("indexCode", TkIndexUtils.getIndexCode(tempIndexValueCode));
//                    tmpVo.put("indexValueCode", tempIndexValueCode);
                    tmpVo.put("indexName", entity.getIndexName());
                    tmpVo.put("indexValueName", entity.getIndexValueName());
                }
                String mType = TkIndexUtils.getMonthType(mirrorCode);
                tmpVo.put(mType, entity.getMTotal());
                tmpVo.put("mTotal", entity.getMTotal());
            }
        }
        log.info("load mirror values, end.");
        for (String indexValueCode : indexValueCodes) {
            Map<String, Object> mapEntity = icMap.get(indexValueCode);
            if(null == mapEntity) {
                log.error("IndexValueVo retVo = null, indexValueCode=" + indexValueCode + ",indexDepart=" + indexDepartCode);
                continue;
            }
            IndexValueVo retVo = (IndexValueVo) EsJsonUtils.map2Bean(mapEntity, IndexValueVo.class);
            if (null == retVo) {
                log.error("IndexValueVo retVo = null, indexValueCode=" + indexValueCode + ",indexDepart=" + mapEntity.get("indexDepart") + ",year=" + mapEntity.get("year"));
                continue;
            }
            if(retVo.getM01() != null){
                retVo.setM01(DepartCode.formateForDouble(retVo.getM01()));
            }
            if(retVo.getM02() != null){
                retVo.setM02(DepartCode.formateForDouble(retVo.getM02()));
            }
            if(retVo.getM03() != null){
                retVo.setM03(DepartCode.formateForDouble(retVo.getM03()));
            }
            if(retVo.getM04() != null){
                retVo.setM04(DepartCode.formateForDouble(retVo.getM04()));
            }
            if(retVo.getM05() != null){
                retVo.setM05(DepartCode.formateForDouble(retVo.getM05()));
            }
            if(retVo.getM06() != null){
                retVo.setM06(DepartCode.formateForDouble(retVo.getM06()));
            }
            if(retVo.getM07() != null){
                retVo.setM07(DepartCode.formateForDouble(retVo.getM07()));
            }
            if(retVo.getM08() != null){
                retVo.setM08(DepartCode.formateForDouble(retVo.getM08()));
            }
            if(retVo.getM09() != null){
                retVo.setM09(DepartCode.formateForDouble(retVo.getM09()));
            }
            if(retVo.getM10() != null){
                retVo.setM10(DepartCode.formateForDouble(retVo.getM10()));
            }
            if(retVo.getM11() != null){
                retVo.setM11(DepartCode.formateForDouble(retVo.getM11()));
            }
            if(retVo.getM12() != null){
                retVo.setM12(DepartCode.formateForDouble(retVo.getM12()));
            }
            if(retVo.getmTotal() != null){
                retVo.setmTotal(DepartCode.formateForDouble(retVo.getmTotal()));
            }
            voResults.add(retVo);
        }
        return voResults;
    }

    public List<TkIndexValueMirrorVo> getMirrorIndexValueEntities(String indexDepartCode, String mirrorCode, List<String> indexValueCodes,String dataType) {

        List<TkIndexValueMirrorVo> results = new ArrayList<>();
        for (String indexValueCode : indexValueCodes) {
            String indexExecutor = getIndexExecutor(indexValueCode);
            TkIndexValueMirrorVo dbEntity;
            dbEntity = getMirrorIndexValueEntity(indexDepartCode, mirrorCode, indexValueCode, indexExecutor,dataType);
            if (null != dbEntity) {
                results.add(dbEntity);
            }
        }
        return results;

    }

    public String getIndexExecutor(String indexValueCode) {
        if (indexValueCode.equals("KCIAAB017VA001") || indexValueCode.equals("KGIAAB017VA001")) {
            // IAAB017 = 重点工作完成
            //todo 通过角色查用户，ykgm和kpiadmin角色可能有多个用户，绩效数据也就可能存在多条，目前取第一个用户（按时间排序）
            Map<String,Object> userQueryMap = new HashMap<>();;
            userQueryMap.put("roleCode","ykgm");
            List<String> userNames = commonMapper.getUserNameByByParam(userQueryMap);
            return userNames.get(0);
        } else if (indexValueCode.equals("KCIAAC005VB001") || indexValueCode.equals("KGIAAC005VB001")) {
            // IAAC005 = 质量改进情况
            //todo 通过角色查用户，ykgm和kpiadmin角色可能有多个用户，绩效数据也就可能存在多条，目前取第一个用户（按时间排序）
            Map<String,Object> userQueryMap = new HashMap<>();;
            userQueryMap.put("roleCode","kpiadmin");
            List<String> userNames = commonMapper.getUserNameByByParam(userQueryMap);
            return userNames.get(0);
        } else {
            return "system";
        }
    }

    public TkIndexValueMirrorVo getMirrorIndexValueEntity(String indexDepartCode, String mirrorCode, String indexValueCode, String indexExecutor,String dataType) {
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("mirrorCode",mirrorCode);
        queryMap.put("indexDepart",indexDepartCode);
        queryMap.put("indexValueCode",indexValueCode);
        queryMap.put("dataType",dataType);
        if (!StringUtils.isEmpty(indexExecutor)) {
            List<String> indexExecutors=new ArrayList<>();
            indexExecutors.add(indexExecutor);
            queryMap.put("indexExecutor", indexExecutors);
        } else {
            log.info("indexDepartCode=" + indexDepartCode + ",mirrorCode=" + mirrorCode + ",indexValueCode=" + indexValueCode);
        }
        return baseMapper.getTkIndexValueMirrorByMirrorCode(queryMap);
    }

    //可查询年份的列表

    /**
     * 需要查询数据库
     */
    private List<YearModel> getYearList(){
        List<SysDictItem> typeList=sysDictItemService.selectItemsByMainId("year");
        List<YearModel> list=new ArrayList<>();
        for (SysDictItem t:typeList){
            YearModel model=new YearModel();
            model.setOption(t.getItemText());
            model.setValue(t.getItemValue());
            list.add(model);
        }
//        List<SysType> typeList=baseMapper.getTsTypeByCode("year");
//        List<YearModel> list=new ArrayList<>();
//        for (SysType t:typeList){
//            YearModel model=new YearModel();
//            model.setOption(t.getTypename());
//            model.setValue(t.getTypecode());
//            list.add(model);
//        }
        return list;
    }

    private List<IndexReportVO>  getIndexReportVOList(HttpServletRequest request,String dataType){
        String reportCode = request.getParameter("userName");//geming
        String userOrgCode=request.getParameter("userOrgCode");//A01A01A01A01
        String queryYear=request.getParameter("queryYear");
        List<String> orgCodes=baseMapper.getOrgCodeAllow(userOrgCode);
        if (!orgCodes.contains(userOrgCode)) {
            orgCodes.add(userOrgCode);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("orgCodes",orgCodes);
        map.put("year",queryYear);
        map.put("dataType",dataType);
        List<TkIndexValue> list= baseMapper.getIndexValueByOrgCodeAllow(map);
        List<IndexReportVO> finalList = new ArrayList<>();
        String indexYearMonth = EsDateUtils.getIndexYearMonth(new Date());
        String yearStr = EsDateUtils.getIndexYear(indexYearMonth);
        String indexGroup ;
        if ("A01A01A01".equals(userOrgCode.substring(0, 9))) {
            indexGroup = "2";
        } else {
            indexGroup = "1";
        }

        Integer reportStatus = null;
        String reportId = null;
        {
            Map<String,String> queryMap=new HashMap<>();
            queryMap.put("indexGroup",indexGroup);
            queryMap.put("reportCode",reportCode);
            queryMap.put("dataType",dataType);
            queryMap.put("indexYearMonth",indexYearMonth);
            TkIndexReport indexReport = baseMapper.getTkIndexReportByReportCode(queryMap);
            if (null != indexReport) {
                reportStatus = indexReport.getReportStatus();
                reportId = indexReport.getId();
            }
        }
        log.info("indexYearMonth=" + indexYearMonth + ",indexGroup=" + indexGroup + ",reportStatus=" + reportStatus);

        for (TkIndexValue item : list) {
            IndexReportVO tkIndexValueBean = new IndexReportVO();
//            tkIndexValueBean.setId(UUID.randomUUID().toString());
            tkIndexValueBean.setIndexDepart(item.getIndexDepart());
            tkIndexValueBean.setIndexCode(item.getIndexCode());
            tkIndexValueBean.setIndexValueCode(item.getIndexValueCode());
            tkIndexValueBean.setReportStatus(reportStatus);

            String indexValueCode = item.getIndexValueCode();
            String indexDepart = item.getIndexDepart();

            Map<String, Double> mTotalMirrorMap = new HashMap<>();
            for (int index = 1; index <= 12; index++) {
                String mirrorCode = TkIndexUtils.getMirrorCode(yearStr, index);
                Map<String,Object> queryMap=new HashMap<>();
                queryMap.put("mirrorCode",mirrorCode);
                queryMap.put("indexDepart",indexDepart);
                queryMap.put("indexValueCode",indexValueCode);
                List<String> indexExecutors=new ArrayList<>();
                indexExecutors.add("system");
                Map<String,Object> userQueryMap = new HashMap<>();
                List<String> roleCodes = new ArrayList<>();
                roleCodes.add("ykgm");
                roleCodes.add("kpiadmin");
                userQueryMap.put("roleCodes",roleCodes);
                List<String> userNames = commonMapper.getUserNameByByParam(userQueryMap);
                indexExecutors.addAll(userNames);
                queryMap.put("indexExecutor",indexExecutors);
                queryMap.put("dataType",dataType);
                TkIndexValueMirrorVo mirrorEntity = baseMapper.getTkIndexValueMirrorByMirrorCode(queryMap);
                if (mirrorEntity != null) {
                    mTotalMirrorMap.put("m" + mirrorCode.substring(6), DepartCode.formateForDouble(mirrorEntity.getMTotal()));
                } else {
                    mTotalMirrorMap.put("m" + mirrorCode.substring(6), 0.0);
                }
            }

            tkIndexValueBean.setM01(mTotalMirrorMap.get("m01") == null ? new Double(0.0) : mTotalMirrorMap.get("m01"));
            tkIndexValueBean.setM02(mTotalMirrorMap.get("m02") == null ? new Double(0.0) : mTotalMirrorMap.get("m02"));
            tkIndexValueBean.setM03(mTotalMirrorMap.get("m03") == null ? new Double(0.0) : mTotalMirrorMap.get("m03"));
            tkIndexValueBean.setM04(mTotalMirrorMap.get("m04") == null ? new Double(0.0) : mTotalMirrorMap.get("m04"));
            tkIndexValueBean.setM05(mTotalMirrorMap.get("m05") == null ? new Double(0.0) : mTotalMirrorMap.get("m05"));
            tkIndexValueBean.setM06(mTotalMirrorMap.get("m06") == null ? new Double(0.0) : mTotalMirrorMap.get("m06"));
            tkIndexValueBean.setM07(mTotalMirrorMap.get("m07") == null ? new Double(0.0) : mTotalMirrorMap.get("m07"));
            tkIndexValueBean.setM08(mTotalMirrorMap.get("m08") == null ? new Double(0.0) : mTotalMirrorMap.get("m08"));
            tkIndexValueBean.setM09(mTotalMirrorMap.get("m09") == null ? new Double(0.0) : mTotalMirrorMap.get("m09"));
            tkIndexValueBean.setM10(mTotalMirrorMap.get("m10") == null ? new Double(0.0) : mTotalMirrorMap.get("m10"));
            tkIndexValueBean.setM11(mTotalMirrorMap.get("m11") == null ? new Double(0.0) : mTotalMirrorMap.get("m11"));
            tkIndexValueBean.setM12(mTotalMirrorMap.get("m12") == null ? new Double(0.0) : mTotalMirrorMap.get("m12"));

            tkIndexValueBean.setmTotal(DepartCode.formateForDouble(item.getMTotal()));
            tkIndexValueBean.setIndexGroup(indexGroup);
            tkIndexValueBean.setReportCode(reportCode);
            tkIndexValueBean.setReportStatus(reportStatus);
            tkIndexValueBean.setReportId(reportId);

            finalList.add(tkIndexValueBean);
        }
        return  finalList;
    }


}
